import java.net.InetAddress;
import java.rmi.Naming;
import java.rmi.RemoteException; 
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.HashMap;

public class Server extends UnicastRemoteObject implements Server_itf {


	/**
	 * 
	 */
	private static final long serialVersionUID = 3615507530877120536L;

	private HashMap<Integer,ServerObject> listServerObject;// the list of the ServerObject created, it contains id and ServerObj
	private HashMap<String, Integer> listName;// the list of the ServerObject created, it contains the id and the name
	private static int id = 0;        // the object's id, you need to increment each time you create a new object

	
	private int generateUniqueId(){
		return id ++;
	}
		
		

		public Server() throws RemoteException{

			this.listServerObject= new HashMap<Integer,ServerObject>();
			this.listName= new HashMap<String, Integer>();

		}

		@Override
		public int lookup(String name) throws RemoteException  {
			Integer i=this.listName.get(name);
			System.out.println("Search for"+name);
			if (i == null){
				System.out.println("l'objet n'existe pas");
				return -1;
				
			}else{
				System.out.println("l'objet existe ");
				return i;
				
			}

			// TODO Auto-generated method stub

		}
		@Override
		public int create(Object o) throws RemoteException {
			int id = generateUniqueId();
			System.out.println(id);
			ServerObject servObj = new ServerObject(id,o);
			listServerObject.put(id, servObj);
			System.out.println("ServerObject with ID = "+id+" is created!");
			return id;

		}

		@Override
		public Object getObject(int id) throws RemoteException {
			return listServerObject.get(id).getObject();
		}


		public Object lock_read(int id, Client_itf client) throws RemoteException {
			ServerObject s= this.listServerObject.get(id);
			return s.lock_read(client);

		}


		@Override

		public Object lock_write(int id, Client_itf client) throws RemoteException {
			ServerObject s= this.listServerObject.get(id);
			return s.lock_write(client);		
		}





		@Override
		public void register(String name, int id) throws RemoteException {
			listName.put(name, id);

			System.out.println("ServerObject with name = "+name+" and id = "+id+" is registered!");
			// TODO Auto-generated method stub


		}

		public static void main(String[] args) {

			try {

				int port = Registry.REGISTRY_PORT;
				String machineName = "localhost";

				Registry r = LocateRegistry.createRegistry(port);
				Server_itf server = new Server();
				String serverURL = "//" + machineName + ":" + port + "/SharedObjectServer";
				Naming.rebind(serverURL, server);
				System.out.println("Server is ready!");

			} catch (Exception e) {
				e.printStackTrace();
			}

		}

	}
